package com.wgo.precise.server.trigger;

import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.log4j.Logger;

import remato.domain.server.ejb.RequirementEjb;

import com.wgo.bpot.common.transport.servicefacade.UniqueValueFactory;
import com.wgo.bpot.domain.common.CrudOperation;
import com.wgo.bpot.server.persist.PersistService;
import com.wgo.bpot.server.persist.trigger.Trigger;

public class BeforeSaveRequirementTrigger implements Trigger<RequirementEjb> {
	private UniqueValueFactory uniqueValueFactory;
	private static final Logger log = Logger.getLogger(BeforeSaveRequirementTrigger.class);
	private static final String REQUIREMENT_ENTITY_TYPE = "requirement";
	private static final int RESERVATION_BUFFER = 5;
	private Queue<Long> reservedBusinessIds = new ConcurrentLinkedQueue<Long>();
	
	
	public void trigger(RequirementEjb triggerTarget) {
		Date now = new Date();
		triggerTarget.setSubmittedDate(now);
		triggerTarget.setLastUpdatedDate(now);
		triggerTarget.setBusinessId(getNextBusinessId());
	}

	public boolean isApplicable(Object persistent) {
		return (null != persistent) && (RequirementEjb.class.isInstance(persistent));
	}

	public boolean isApplicable(CrudOperation operation) {
		return CrudOperation.CREATE.equals(operation);
	}

	public boolean isBefore() {
		return true;
	}

	private Long getNextBusinessId(){
		if (reservedBusinessIds.isEmpty()) {
			reservedBusinessIds.addAll(uniqueValueFactory.getNextReservedValues(REQUIREMENT_ENTITY_TYPE,RESERVATION_BUFFER));
			log.info("Reserved " + RESERVATION_BUFFER + " new requirement business IDs, starting at #" + reservedBusinessIds.peek());
		}
		return reservedBusinessIds.poll();
	}

	public void setPersistService(PersistService persistService) {
		this.uniqueValueFactory = persistService.getUniqueValueFactory();
	}
	
}
